<?php
/**
 * @version 1.0 上传逻辑类
 * @internal
 * @link
 * @property
 * @see
 * @since
 * @uses
 *
 */
namespace app\user\logic;

use app\Api;
use app\user\logic\Oss as IndexLogicOss;

class Upload extends Api
{
    private static $obj = null;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 类入口
     * @return Upload|null
     */
    public static function getInstance()
    {
        if (is_null(self::$obj))
            self::$obj = new self();
        return self::$obj;
    }

    /**
     * 文件上传
     * @param $path string 文件保存路径
     * @return array|bool
     */
    public function saveFile($path = 'file')
    {
        $res = false;
        $filePath = [];
        foreach ($_FILES as $key => $value) {
            if (is_array($value['tmp_name'])) {
                foreach ($value['tmp_name'] as $k => $val) {
                    $fileNewPath = $path . '/' . date('Ymd', time()) . '/' . (date('YmdHis', time()) . rand(1000, 9999)) . "." . substr($value['name'][$k], strripos($value['name'][$k], '.') + 1);
                    $res = IndexLogicOss::getInstance()->uploadFile($fileNewPath, $value['tmp_name'][$k]);
                    $filePath[] = config('oss.url') . '/' . $fileNewPath;
                }
            } else if (is_string($value['tmp_name'])) {
                $fileNewPath = $path . '/' . date('Ymd', time()) . '/' . (date('YmdHis', time()) . rand(1000, 9999)) . "." . substr($value['name'], strripos($value['name'], '.') + 1);
                $res = IndexLogicOss::getInstance()->uploadFile($fileNewPath, $value['tmp_name']);
                $filePath = (string)config('oss.url') . '/' . $fileNewPath;
            }
        }
        if ($res)
            return $filePath;
        return false;
    }
}
